<?php

namespace App\Http\Controllers\Network;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\GoodsOrderDetailModel;
use App\Models\yb\GoodsOrderModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\NetworkCreditRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\SettingModel;
use App\Models\yb\UserAddressModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use EasyWeChat\Factory;


class OrderController extends Controller
{


    /**
     * Get a JWT via given credentials.
     *  订单列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderListing(Request $request){

        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid'=>$openid])->first();

        if(empty($user_data) || empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $status = $request->post('status', 0);

        if($user_data['type'] == 3){
            if(empty($status)){
                $data = GoodsOrderModel::where(['staff_id'=>$user_data['id']])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }else{
                $data = GoodsOrderModel::where(['staff_id'=>$user_data['id'],'status'=>$status])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }
        }else{
            if(empty($status)){
                $data = GoodsOrderModel::where(['network_id'=>$user_data['id']])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }else{
                $data = GoodsOrderModel::where(['network_id'=>$user_data['id'],'status'=>$status])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
            }
        }

        foreach($data as $key=>$val){
            $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$val['order_sn']])->get();
            $goods_list = [];
            $goods_count = 0;
            foreach($goods_order_detail as $k=>$v){
                $goods_count = $goods_count+$v['number'];
                $goods_data = GoodsModel::where(['id'=>$v['goods_id']])->first();
                $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
                $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
                $goods_list[]=$goods_data;
            }

            $data[$key]['goods_data']  = $goods_list;

            $data[$key]['goods_count']  = $goods_count;
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  商品下单详情
     * @return \Illuminate\Http\JsonResponse
     */

    public function OrderDetails(Request $request){

        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid'=>$openid])->first();

        if(empty($user_data) || empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($order_data)){
            return response()->json(['code'=>'203','msg' => '订单不存在']);
        }

        $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$order_data['order_sn']])->get();

        $goods_list = [];
        foreach($goods_order_detail as $k=>$v){
            $goods_data = GoodsModel::where(['id'=>$v['goods_id']])->first();
            $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
            $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
            $goods_data['water_ticket_deduction_number'] = $v['water_ticket_deduction_number'];
            $goods_data['coupon_deduction'] =$v['coupon_deduction'];
            $goods_data['number'] =$v['number'];
            $goods_list[]=$goods_data;
        }
        $user_address_data = UserAddressModel::where(['id'=>$order_data['address_id']])->first();

        $setting_data = SettingModel::select(['customer_phone'])->first();

        $staff_data = AdminUserModel::where(['id'=>$order_data['staff_id']])->first();

        $order_data['staff_name'] = isset($staff_data['name'])?$staff_data['name']:"";
        $order_data['staff_mobile'] = isset($staff_data['mobile'])?$staff_data['mobile']:"";


        $data['order_data'] = $order_data;
        $data['goods_data'] = $goods_list;
        $data['user_address_data'] = $user_address_data;
        $data['setting_data'] = $setting_data;

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  订单接单
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderReceiving(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $staff_id = $request->post('staff_id');
        if(empty($staff_id)) {
            return response()->json(['code' => '203', 'msg' => '请指派送水师傅']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($order_data) || $order_data['status'] !=1){
            return response()->json(['code'=>'203','msg' => '已被他人接单']);
        }

        $staff_data = AdminUserModel::where(['id'=>$staff_id])->select('wechat_openid')->first();

        if(!empty($staff_data['wechat_openid'])){
            GoodsOrderModel::orderPush($staff_data['wechat_openid'],$order_sn);
        }

        GoodsOrderModel::where(['order_sn'=>$order_sn])->update([
            'status'=>2,
            'network_id'=>$user_data['id'],
            'network_openid'=>$user_data['openid'],
            'staff_id' => $staff_id
        ]);

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }


    /**
     * Get a JWT via given credentials.
     *  订单送达
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderService(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn' => $order_sn])->first();

        if(empty($order_data) || $order_data['status'] != 2){
            return response()->json(['code'=>'203','msg' => '订单已确认']);
        }

        $goods_detail_data = GoodsOrderDetailModel::where(['order_sn'=>$order_sn])->get();

        DB::beginTransaction();

        GoodsOrderModel::where(['order_sn'=>$order_sn])->update([
            'status'=>3,
            'service_date'=>date('Y-m-d H:i:s',time())
        ]);

        $network_credit_record_data =[];

        foreach($goods_detail_data as $key=>$val){

            NetworkGoodsModel::where(['network_id'=>$order_data['network_id'],'goods_id'=>$val['goods_id']])->increment('return_credit',$val['number']);
            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->first();
            $network_credit_record_data[] = [
                'network_id' => $order_data['network_id'],
                'goods_id' => $val['goods_id'],
                'number' => $val['number'],
                'amount' => $goods_data['retail_goods_price']* $val['number'],
                'remark' => '售卖商品',
                'status' => 1,
                'relation_data' => $order_sn,
                'type' => 2,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->select(['distribution_fee'])->first();

            AdminUserModel::where(['id'=>$order_data['network_id']])->increment('distribution_price',$goods_data['distribution_fee']);

            $network_credit_record_data[] = [
                'network_id' => $order_data['network_id'],
                'goods_id' => $val['goods_id'],
                'number' => $val['number'],
                'amount' =>$goods_data['distribution_fee'],
                'remark' => '售卖商品',
                'status' => 1,
                'relation_data' => $order_sn,
                'type' => 4,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
        }

        NetworkCreditRecordModel::insert($network_credit_record_data);

        $config = [
            'app_id' => env('WECHAT_CLIENT_APP_ID'),  // 这里需要自行修改
            'secret' => env('WECHAT_CLIENT_APP_SECRET'),  // 这里需要自行修改
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => 'wechat.log',
            ],
        ];
        $app = Factory::miniProgram($config);

        $user_address = UserAddressModel::where(['id'=>$order_data['address_id']])->first();

        $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$order_sn])->get();
        $goods_data_str = "";
        foreach($goods_order_detail as $key=>$val){
            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->first();
            $goods_data_str = $goods_data_str.",".mb_substr($goods_data['goods_title'],6);
        }
        $goods_data_str = mb_substr($goods_data_str,1);

        $staff_data = AdminUserModel::where(['id'=>$order_data['staff_id']])->first();
        
        if(!empty($user_address)){
             $data = [
                'template_id' => '_vi9FPk9T890fkO1idakNTlzYlmBFiqAPogPCoi0HvU', // 所需下发的订阅模板id
                'touser' => $order_data['openid'],     // 接收者（用户）的 openid
                'page' => '/pages/index/order',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'thing1' => array('value' => $user_address['address']),
                    'time2' =>array('value'=> date('Y-m-d H:i:s',time())),
                    'thing3' => array('value' => $goods_data_str),
                    'thing4' => array('value' => $staff_data['name']),
                    'phone_number5' => array('value' => $staff_data['mobile']),
                ],
            ];
        $aa = $app->subscribe_message->send($data);
        
        }
       
        DB::commit();

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }



}
